﻿using System;
using System.Web.UI.WebControls;
using DBProvider.Providers;
using DBProvider;
using System.Collections.Generic;
using System.Collections;

namespace HealthCommunity.Controls
{
	public partial class UCActivityList : System.Web.UI.UserControl
	{
		private IActivityProvider _ActivityProvider;

		/// <summary>
		/// 1: 所有
		/// 2: 我发布的
		/// 3: 我参加的
		/// </summary>
		public int ActivityGetType
		{
			get;
			set;
		}

		private IList<Activity> _DataSource;
		private int _TotalRecords;

		public IList<Activity> DataSourse
		{
			get
			{
				var pageIndex = this.PageIndex;
				var totalRecords = 0;
				var pageSize = this.PageSize;

				var selectedItem = ddlActivityCategory.SelectedValue;

				if(!string.IsNullOrEmpty(selectedItem))
				{
					int selectedActCatID = int.Parse(selectedItem);

					if(_ActivityProvider == null)
					{
						_ActivityProvider = new ActivityProvider();
					}

					List<Activity> data = null;

					var userID = 0;
					var user = SiteContext.Current.CurrentUser;

					if(user != null)
					{
						userID = SiteContext.Current.CurrentUser.UserID;
					}

					if(userID > 0)
					{
						if(selectedActCatID > 0)
						{
							if(ActivityGetType == 3)
							{
								data = _ActivityProvider.GetMyRegistrationActivity(userID, selectedActCatID, pageIndex, pageSize, out totalRecords);
							}
							else if(ActivityGetType == 2)
							{
								data = _ActivityProvider.GetMyInitiatActivity(userID, selectedActCatID, pageIndex, pageSize, out totalRecords);
							}
							else
							{
								if(user.Role.RoleName.ToLower().Equals("admin"))
								{
									var drugstore = SiteContext.Current.CurrentDrugStore;

									if(drugstore != null)
									{
										data = _ActivityProvider.GetActivityByCategory(selectedActCatID, drugstore.DrugStoreID, pageIndex, pageSize, out totalRecords);
									}
								}
								else
								{
									if(user.DrugStoreID.GetValueOrDefault(0) > 0)
									{
										data = _ActivityProvider.GetActivityByCategory(user.UserID, selectedActCatID, user.DrugStoreID.Value, pageIndex, pageSize, out totalRecords);
									}
								}
							}
						}
						else
						{
							if(ActivityGetType == 3)
							{
								data = _ActivityProvider.GetMyRegistrationActivity(userID, pageIndex, pageSize, out totalRecords);
							}
							else if(ActivityGetType == 2)
							{
								data = _ActivityProvider.GetMyInitiatActivity(userID, pageIndex, pageSize, out totalRecords);
							}
							else
							{
								if(user.Role.RoleName.ToLower().Equals("admin"))
								{
									var drugstore = SiteContext.Current.CurrentDrugStore;

									if(drugstore != null)
									{
										data = _ActivityProvider.GetAllActivity(drugstore.DrugStoreID, pageIndex, pageSize, out totalRecords);
									}
								}
								else
								{
									if(user.DrugStoreID.GetValueOrDefault(0) > 0)
									{
										data = _ActivityProvider.GetAllActivity(user.UserID, user.DrugStoreID.Value, pageIndex, pageSize, out totalRecords);
									}
								}
							}
						}
					}
					else
					{
						//if (ActivityGetType == 1)
						//{
						//   if (selectedActCatID > 0)
						//   {
						//      data = _ActivityProvider.GetActivityByCategory(selectedActCatID);
						//   }
						//   else
						//   {
						//      data = _ActivityProvider.GetAllActivity();
						//   }
						//}
					}

					_DataSource = data;
				}

				this.TotalRecords = totalRecords;

				return _DataSource;
			}
		}

		public int PageIndex
		{
			get
			{
				if(ViewState["PageIndex"] == null)
				{
					return 0;
				}
				else
				{
					return int.Parse(ViewState["PageIndex"].ToString());
				}
			}
			set
			{
				ViewState["PageIndex"] = value;
			}
		}

		public int TotalRecords
		{
			get
			{
				return _TotalRecords;
			}
			set
			{
				_TotalRecords = value;
			}
		}

		public int TotalPages
		{
			get
			{
				var data = _DataSource == null ? this.DataSourse : _DataSource;

				if(data == null)
				{
					return 0;
				}

				int totalRecords = TotalRecords;

				int totalPages = 0;

				if(totalRecords <= PageSize)
				{
					totalPages = 1;
				}

				if(totalRecords % PageSize == 0)
				{
					totalPages = totalRecords / PageSize;
				}

				if(totalRecords % PageSize > 0)
				{
					totalPages = totalRecords / PageSize + 1;
				}

				return totalPages;
			}
		}

		public int PageSize
		{
			get
			{
				return int.Parse(ddlPageSize.SelectedValue);
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				BindActivityCategory();
			}
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			BindActivity();

			var currentPageIndex = this.PageIndex;
			var totalPages = TotalPages;

			// set pager index links
			List<PagerIndex> indexs = new List<PagerIndex>();

			if(totalPages <= 25)
			{
				for(int i = 1; i <= totalPages; i++)
				{
					indexs.Add(new PagerIndex(i.ToString()));
				}
			}
			else
			{
				for(var i = 13; i > 0; i--)
				{
					if(indexs.Count >= 27)
					{
						break;
					}

					var index = currentPageIndex - i;

					if(index > 0)
					{
						indexs.Add(new PagerIndex(index.ToString()));
					}
				}

				for(var i = 0; i <= 13; i++)
				{
					if(indexs.Count > 27)
					{
						break;
					}

					var index = currentPageIndex + i;

					if(index <= totalPages && index > 0)
					{
						indexs.Add(new PagerIndex(index.ToString()));
					}
				}
			}

			this.RptrPageIndex.DataSource = indexs;
			this.RptrPageIndex.DataBind();

			this.LabelTotalPages.Text = totalPages.ToString();
			this.LabelTotalRecords.Text = TotalRecords.ToString();

			// disenabel the current pagerindex link
			if(RptrPageIndex.Items.Count > 0)
			{
				for(int i = 0; i < RptrPageIndex.Items.Count; i++)
				{
					LinkButton thePagerIndexLink = RptrPageIndex.Items[i].FindControl("LBPageIndex") as LinkButton;

					if(thePagerIndexLink.Text.Trim().Equals((currentPageIndex + 1).ToString()))
					{
						thePagerIndexLink.Enabled = false;
					}
				}
			}

			lbtnFirstPage.Enabled = (currentPageIndex > 0);

			lbtnLastPage.Enabled = totalPages > 1 && (currentPageIndex != totalPages - 1);

			var u = SiteContext.Current.CurrentUser;

			btnDelSelected.Visible = false;
			gvActivity.Columns[0].Visible = false;

			if (u != null && u.Role != null)
			{
				btnDelSelected.Visible = u.Role.RoleName.ToLower().Equals("storeadmin") || u.Role.RoleName.ToLower().Equals("storemanager") || u.Role.RoleName.ToLower().Equals("admin");
				gvActivity.Columns[0].Visible = u.Role.RoleName.ToLower().Equals("storeadmin") || u.Role.RoleName.ToLower().Equals("storemanager") || u.Role.RoleName.ToLower().Equals("admin");
			}
		}

		protected void LBPageIndex_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			switch(e.CommandName)
			{
				case "PageIndex":
					{
						LinkButton theLink = sender as LinkButton;

						int index = int.Parse(theLink.Text);

						PageIndex = index - 1;

						//TotalRecords = DataSource.Count();

						BindActivity();
					}
					break;
			}
		}

		protected void lbtnFirstPage_Click(object sender, EventArgs e)
		{
			PageIndex = 0;
			BindActivity();
		}

		protected void lbtnLastPage_Click(object sender, EventArgs e)
		{
			PageIndex = TotalPages - 1;
			BindActivity();
		}

		protected void ddlExmtCat_SelectedIndexChanged(object sender, EventArgs e)
		{
			//BindExamination();
		}

		protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
		{
			this.PageIndex = 0;
		}

		protected void btnDelSelected_Click(object sender, EventArgs e)
		{
			var ids = new List<int>();

			foreach (GridViewRow row in gvActivity.Rows)
			{
				var chbActivity = row.FindControl("chbActivity") as CheckBox;

				if (chbActivity.Checked)
				{
					var hfActivityID = row.FindControl("hfActivityID") as HiddenField;

					var id = 0;
					if (int.TryParse(hfActivityID.Value, out id))
					{
						ids.Add(id);
					}
				}
			}

			if (ids.Count > 0)
			{
				if (_ActivityProvider == null)
				{
					_ActivityProvider = new ActivityProvider();
				}

				if (_ActivityProvider.DeleteActivity(ids))
				{
					ltrMsg.Text = "删除成功";
					//BindActivity();
				}
				else
				{
					ltrMsg.Text = "删除遇到错误";
				}
			}
		}

		protected void ddlActivityCategory_SelectedIndexChanged(object sender, EventArgs e)
		{
			//BindActivity();
		}

		protected void gvActivity_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				var hfActivityID = e.Row.FindControl("hfActivityID") as HiddenField;
				var hlActivity = e.Row.FindControl("hlActivity") as HyperLink;
				var dataItem = e.Row.DataItem as Activity;

				if (dataItem != null)
				{
					hfActivityID.Value = dataItem.ActivityID.ToString();
					hlActivity.Text = dataItem.ActivityTitle;
					hlActivity.NavigateUrl = "~/ActivityDetail.aspx?activityid=" + dataItem.ActivityID.ToString();
				}
			}
		}

		private void BindActivityCategory()
		{
			if (_ActivityProvider == null)
			{
				_ActivityProvider = new ActivityProvider();
			}

			ddlActivityCategory.Items.Clear();

			ddlActivityCategory.DataSource = _ActivityProvider.GetAllActivityCategory();
			ddlActivityCategory.DataBind();

			ddlActivityCategory.Items.Insert(0, new ListItem("全部", "0"));
			ddlActivityCategory.SelectedIndex = 0;
		}

		private void BindActivity()
		{
			var data = this.DataSourse;

			gvActivity.DataSource = data;
			gvActivity.DataBind();
		}
	}
}